package com.devilwwj.androiddevelopcourse.activities;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;

import com.devilwwj.androiddevelopcourse.R;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Raw资源
 */
public class RawResTestActivity extends ActionBarActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) this.findViewById(R.id.tv_hello);
        readRaw();

    }


    public void readAssets() {
        AssetManager assetManager = getAssets();
        try {
            InputStream inputStream = assetManager.open("demo.txt");
            textView.setText(read(inputStream));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void readRaw() {
        InputStream inputStream = getResources().openRawResource(R.raw.demo);
        textView.setText(read(inputStream));
    }

    private String read(InputStream inputStream) {
        try {
            ByteArrayOutputStream osStream = new ByteArrayOutputStream();
            int length;
            while ((length = inputStream.read()) != -1) {
                osStream.write(length);
            }
            return osStream.toString();
        } catch (IOException e) {
            return "文件读写失败";
        }
    }
}
